package mju.cxf.controller.user;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import mju.cxf.context.BaseContext;
import mju.cxf.dto.UserDTO;
import mju.cxf.dto.UserLoginDTO;
import mju.cxf.entity.Credit;
import mju.cxf.entity.Integral;
import mju.cxf.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mju.cxf.constant.JwtClaimsConstant;
import mju.cxf.constant.MessageConstant;
import mju.cxf.enumeration.ImageType;
import mju.cxf.properties.JwtProperties;
import mju.cxf.result.Result;
import mju.cxf.service.CreditService;
import mju.cxf.service.IntegralService;
import mju.cxf.service.PhotoService;
import mju.cxf.service.UserService;
import mju.cxf.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import mju.cxf.vo.UserLoginVO;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user/api/user")
@Api(tags = "用户接口列表")
@Slf4j
public class IUserController {
    @Autowired
    private UserService userService;
    @Autowired
    private PhotoService photoService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private IntegralService integralService;
    @Autowired
    private CreditService creditService;
    private static final int scope=85;
    @PostMapping("/userInfo")
    public Result<HashMap<String,Object>> userInfo() {
        final User user = userService.getById(BaseContext.getCurrentId());
        LambdaQueryWrapper<Integral> iqw1 = new LambdaQueryWrapper<>();
        iqw1.eq(Integral::getUserId, BaseContext.getCurrentId())
                .eq(Integral::getType, 1)  // 查询 type 等于 1 的记录
                .orderByDesc(Integral::getCreateTime);

        LambdaQueryWrapper<Integral> iqw2 = new LambdaQueryWrapper<>();
        iqw2.eq(Integral::getUserId, BaseContext.getCurrentId())
                .eq(Integral::getType, 2)  // 查询 type 等于 2 的记录
                .orderByDesc(Integral::getCreateTime);

        LambdaQueryWrapper<Integral> iqw3 = new LambdaQueryWrapper<>();
        iqw3.eq(Integral::getUserId, BaseContext.getCurrentId())
                .eq(Integral::getType, 3)  // 查询 type 等于 3 的记录
                .orderByDesc(Integral::getCreateTime);
        List<Integral> integralsType1 = integralService.list(iqw1);
        List<Integral> integralsType2 = integralService.list(iqw2);
        List<Integral> integralsType3 = integralService.list(iqw3);

        LambdaQueryWrapper<Credit> cqw= new LambdaQueryWrapper<>();
        cqw.eq(Credit::getId, BaseContext.getCurrentId());
//        integralService.list(cqw);
        HashMap<String,Object> userInfo = new HashMap<>();
        userInfo.put("userInfo",user);
        userInfo.put("integral",integralsType1);
        userInfo.put("member",integralsType2);
        userInfo.put("credit",integralsType3);
        //TODO 还有其他个人信息展示
//        userInfo.put("credit",integrals);
        return Result.success(userInfo);
    }

    /**
     * U微信登陆接口
     * @param userLoginDTO 登陆数据
     * @return rest返回值
     */
    @PostMapping("/wxLogin")
@ApiOperation("微信登陆接口")
public Result<UserLoginVO> userLogin(@RequestBody UserLoginDTO userLoginDTO)  {
    log.info("微信用户登陆：{}",userLoginDTO.getCode());
    System.out.println(userLoginDTO);
    Map<String, Object> claims=new HashMap<>();
    User user = userService.wxLogin(userLoginDTO);
    claims.put(JwtClaimsConstant.JWT_ID,user.getId());
    claims.put(JwtClaimsConstant.ROLE,"USER");
    //生成令牌
    String token = JwtUtil.createJWT( jwtProperties.getJwtSecretKey(),jwtProperties.getJwtTtl(), claims);
    UserLoginVO userLoginVO=UserLoginVO.builder()
            .userInfo(user)
            .token(token)
            .build();
    return Result.success(userLoginVO);
}
    /**
     * U绑定邮箱
     *
     * @param userLoginDto 用户信息
     * @return 返回包含用户信息和 token 的结果
     */
    @PostMapping("/bind")
    @ApiOperation(value = "绑定邮箱接口", notes = "用户通过此接口进行绑定邮箱")
    public Result<String> bind(@RequestBody UserLoginDTO userLoginDto) {
         userService.bind(userLoginDto);
        return Result.success();
    }

    /**
     * 签到
     * @return 返回签到信息
     */
    @PostMapping("/sign")
    public Result<String> sign() {
        String msg=userService.signIn();
        return msg.equals(MessageConstant.SUCCESS_MESSAGE)? Result.success(msg):Result.error(msg);
    }
    /**
     * U修改用户信息
     *
     * @param userDTO
     * @return
     */
    @PutMapping
    @ApiOperation(value = "修改用户信息", notes = "管理员通过此接口修改用户信息")
    public Result<String> updateUser(@RequestPart MultipartFile multipartFile, @RequestBody UserDTO userDTO) {
        return userService.updateUser(userDTO) ?
                Result.success(MessageConstant.SUCCESS_MESSAGE) :
                Result.error(MessageConstant.FAILURE_MESSAGE);
    }

    /**
     * U接收上传的文件和修改用户数据
     * @param file    上传的文件
     * @param userDTO 用户信息
     * @return 操作结果
     */
    @PostMapping("/updateInfo")
    @ApiOperation(value = "修改用户信息", notes = "管理员通过此接口修改用户信息")
    public Result<String> uploadFile(@RequestPart MultipartFile file, @RequestPart UserDTO userDTO) {
        try {
            // 处理文件上传
            String avatarUrl = photoService.uploadImg(file, ImageType.AVATAR.getPath());
            // 此处可以根据需要处理用户信息
            userDTO.setAvatar(avatarUrl);
            return userService.updateUser(userDTO) ?
                    Result.success(MessageConstant.SUCCESS_MESSAGE) :
                    Result.error(MessageConstant.FAILURE_MESSAGE);
        } catch (Exception e) {
            return Result.error(MessageConstant.IO_FAILED);
        }
    }

    /**
     * 获取信用分
     * @return
     */
    @PostMapping("/credit")
    public Result<String> credit(){
        LambdaQueryWrapper<User> uqw=new LambdaQueryWrapper<>();
        uqw.eq(User::getId, BaseContext.getCurrentId());
        final User user = userService.getOne(uqw);
        if (user.getCredit()>=scope) {
            return Result.success();
        }else{
            return Result.error(MessageConstant.INSUFFICIENT_CREDIT_SCORE);
        }

    }

    /**
     * 金额提现
     * @return
     */
    @PostMapping("/payouts")
    public Result<String> payouts(){
        LambdaUpdateWrapper<User> uuw=new LambdaUpdateWrapper<>();
        //全部提现
        uuw.eq(User::getId, BaseContext.getCurrentId()).set(User::getAvailableBalance,0);
        return userService.update(uuw)?Result.success(MessageConstant.SUCCESS_MESSAGE):Result.error(MessageConstant.FAILURE_MESSAGE);
    }
    /**
     *
     */
    @PostMapping("/level")
    public Result<Integer> level(){
        final User user = userService.getById(BaseContext.getCurrentId());
        final Double member = user.getMember();
        int level=0;
        if (member>=100 && member<500){
            level=1;
        } else if (member>=500) {
            level=2;
        }
        return Result.success(level);
    }
}

